from collections import namedtuple
from django.db import connection
from django.db import utils as u
from .cookie import *
from django.shortcuts import render
from django.utils import timezone

from django.http import HttpResponse, JsonResponse
from rest_framework.decorators import api_view
from rest_framework import permissions
from .serializers import *
from rest_framework.response import Response
from .models import *
import json


# Create your views here.

# 将Json格式的数据转化成Object
def UnJson(jsonData):
    json_str = json.dumps(jsonData)
    data = json.loads(json_str, object_hook=lambda d: namedtuple('data', d.keys())(*d.values()))
    return data


# 将mysql table格式的数据转JSON
def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]


#####cookie


#############################################################两者操作


###消费者查找聊天记录
@api_view(['POST'])
def ChatList(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        saleraccount = str(data.oaccount)
        cursor.execute(
            "select * from chat where (sender=" + customeraccount + " and receiver=" + saleraccount + ") or (sender=" + saleraccount + " and receiver=" + customeraccount + ") order by chatDate")
        rows = dictfetchall(cursor)
        Chat.objects.filter(receiver = Accountmanage.objects.get(pk=customeraccount),
                            sender = Accountmanage.objects.get(pk = saleraccount)).update(chatstatus ='read')
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###销售商查找聊天记录
@api_view(['POST'])
def salerChat(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        customeraccount = str(data.customeraccount)
        cursor.execute(
            "select * from chat where (sender=" + customeraccount + " and receiver=" + saleraccount + ") or (sender=" + saleraccount + " and receiver=" + customeraccount + ")")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###查找最近一次聊天记录
@api_view(['POST'])
def CusrecentChat(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        account = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from chat a where (a.sender=" + account + " or a.receiver=" + account + ") and chatDate>=all(select chatDate from chat b where (b.sender=" + account +
            " and b.receiver=a.receiver)or (b.receiver=" + account + " and b.sender=a.sender))")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###############################################################################消费者操作###############################

###查看所有产品
@api_view(['GET'])
def allProduct(request):
    cursor = connection.cursor()
    cursor.execute(
        "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount")
    rows = dictfetchall(cursor)
    return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})


###搜索产品
@api_view(['POST'])
def query(request):
    # 接收前端传来数据
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        account = get_username(data.token)
        role = get_username(data.token)
        productname = str(data.productname)
        # 从数据库中查找并返回
        cursor = connection.cursor()
        cursor.execute(
            "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount and productname like '%" + productname + "%'")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###浏览固定店铺
@api_view(['POST'])
def myStore(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        # saleraccount = get_username(data.token)
        saleraccount = str(data.saleraccount)
        cursor = connection.cursor()
        cursor.execute(
            "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount and saler.saleraccount=" + saleraccount)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###浏览单个产品信息并加入历史记录
@api_view(['POST'])
def uniproduct(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        saleraccount = str(data.saleraccount)
        productno = str(data.productno)
        # token = str(data.token)

        cursor = connection.cursor()
        # 加入历史浏览记录
        # cursor.execute(
        #     "insert into history(customeraccount，saleraccount，productno) values(" + customeraccount + "," + saleraccount + "," + productno + ")")

        History.objects.create(customeraccount=Customer.objects.get(customeraccount=customeraccount),
                               saleraccount=Saler.objects.get(saleraccount=saleraccount),
                               productno=Product.objects.get(productno=productno),
                               historydate=timezone.now())
        cursor.execute(
            "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount and saler.saleraccount=" + saleraccount + " and product.productno=" + productno)
        row = dictfetchall(cursor)
        return JsonResponse(row, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###查看历史浏览记录
@api_view(['POST'])
def viewhistory(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from history,sale,product,saler where history.saleraccount=sale.saleraccount and sale.productno=history.productno and history.productno=product.productno "
            "and sale.productno=product.productno and saler.saleraccount=sale.saleraccount and customeraccount= " + customeraccount + " order by historyDate")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###收藏店铺
@api_view(['POST'])
def collectStore(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        saleraccount = str(data.saleraccount)
        cursor = connection.cursor()
        cursor.execute(
            "insert into collection(customeraccount,saleraccount) values(" + customeraccount + "," + saleraccount + ")")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###直接购买
@api_view(['POST'])
def directBuy(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        # 这里开始写你的功能
        saleraccount = str(data.saleraccount)
        # customeraccount = str(data.customeraccount)
        productno = str(data.productno)
        quantity = int(data.quantity)
        uniprice = int(data.uniprice)
        total = quantity * uniprice
        # 做一个余额比较

        C = Accountmanage.objects.get(pk=customeraccount)
        if(Customer.objects.get(pk=C).balance < total):
            res = {'code': 201, 'message': '余额不足请充值'}
            return HttpResponse(json.dumps(res))
        S = Accountmanage.objects.get(pk=saleraccount)
        Order = Saleorder.objects.create(customeraccount=C,
                                         pk=time.strftime('%Y%m%d%H%M%S',
                                                          time.localtime(time.time())) + customeraccount,
                                         saleraccount=S,
                                         totalprice=total,
                                         orderdate=time.strftime('%Y-%m-%d %X', time.localtime(time.time())),
                                         orderstatus='unshipped')
        print('orderDone')
        P = Product.objects.get(pk=productno)
        Include.objects.create(orderno=Order, productno=P, buyquantity=quantity)
        res = {'code': 200, 'message': '购买成功'}
        return HttpResponse(json.dumps(res))
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


##加入购物车
@api_view(['POST'])
def insertShoppingCar(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        saleraccount = str(data.saleraccount)
        productno = str(data.productno)
        quantity = int(data.quantity)
        # cursor = connection.cursor()
        # cursor.callproc('insertShoppingCar', (saleraccount, customeraccount, productno, quantity))
        # rows = dictfetchall(cursor)
        C = Accountmanage.objects.get(pk=customeraccount)
        S = Accountmanage.objects.get(pk=saleraccount)
        P = Product.objects.get(pk=productno)
        try:
            Shoppingcar.objects.create(customeraccount=C,
                                       saleraccount=S,
                                       productno=P,
                                       quantity=quantity)
        except u.IntegrityError:  # 如果以及在购物车里
            print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
            new = Shoppingcar.objects.filter(customeraccount=C,
                                          saleraccount=S,
                                          productno=P)
            new.update(quantity = new[0].quantity+quantity)
        else:
            print('wdnmd!')
        res = {'code': 200, 'message': '加入购物车成功'}
        return HttpResponse(json.dumps(res))
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###查看购物车
@api_view(['POST'])
def viewCar(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select sale.saleraccount,shoppingCar.customeraccount,saler.address,sale.pic1,sale.pic2,product.productclassify,sale.productintroduction,product.productname,"
            "product.productno,shoppingCar.quantity,sale.sales,saler.score,saler.storename,sale.unitprice from shoppingCar,saler,sale,product where "
            "shoppingCar.productno=product.productno and shoppingCar.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount "
            "and sale.productno=product.productno and customeraccount= " + customeraccount + " order by sale.saleraccount")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})

    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###选中购物车内部分产品
@api_view(['POST'])
def selFromCar(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        saleraccount = str(data.saleraccount)
        productno = str(data.productno)
        cursor = connection.cursor()
        # cursor.execute("update shoppingcar set checked='checked' where saleraccount="+ saleraccount + "and customeraccount= " + customeraccount + " and productno=" + productno);
        cursor.execute(
            "update shoppingCar set checked='checked' where saleraccount=" + saleraccount + " and customeraccount=" + customeraccount + " and productno=" + productno);
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###取消选择购物车内部分产品
@api_view(['POST'])
def delFromCar(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        saleraccount = str(data.saleraccount)
        productno = str(data.productno)
        cursor = connection.cursor()
        # cursor.execute("update shoppingcar set checked='checked' where saleraccount="+ saleraccount + "and customeraccount= " + customeraccount + " and productno=" + productno);
        cursor.execute(
            "update shoppingCar set checked='unchecked' where saleraccount=" + saleraccount + " and customeraccount=" + customeraccount + " and productno=" + productno);
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###批量删除
@api_view(['POST'])
def delAll(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        productno = str(data.productno)
        cursor = connection.cursor()
        cursor.execute("delete from shoppingCar where customeraccount= " + customeraccount + " and checked='checked'");
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 从购物车下单
@api_view(['POST'])
def placeOrder(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        saleraccount = str(data.saleraccount)
        role = get_username(data.token)
        cursor = connection.cursor()
        print(customeraccount)
        cursor.callproc('placeOrder', (customeraccount, saleraccount))
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 从购物车购买
@api_view(['POST'])
def buyFromCar(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法

        customeraccount = get_username(data.token)
        saleraccount = str(data.saleraccount)
        total = 0
        for item in data.list:
            total += item.quantity * int(item.unitprice)
        # 做一个余额比较
        C = Accountmanage.objects.get(pk=customeraccount)
        if (Customer.objects.get(pk=C).balance < total):
            res = {'code': 201, 'message': '余额不足请充值'}
            return HttpResponse(json.dumps(res))
        S = Accountmanage.objects.get(pk=saleraccount)
        Order = Saleorder.objects.create(customeraccount=C,
                                         pk=time.strftime('%Y%m%d%H%M%S',
                                                          time.localtime(time.time())) + customeraccount,
                                         saleraccount=S,
                                         totalprice=total,
                                         orderdate=time.strftime('%Y-%m-%d %X', time.localtime(time.time())),
                                         orderstatus='unshipped')
        print('orderDone')
        for item in data.list:
            P = Product.objects.get(pk=item.productno)
            Include.objects.create(orderno=Order, productno=P, buyquantity=item.quantity)
            Shoppingcar.objects.filter(customeraccount=C, saleraccount=S, productno=P).delete()
        res = {'code': 200, 'message': '购买成功'}
        return HttpResponse(json.dumps(res))


    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 从购物车删除
@api_view(['POST'])
def delFromCar(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法

        customeraccount = get_username(data.token)
        saleraccount = str(data.saleraccount)
        C = Accountmanage.objects.get(pk=customeraccount)
        S = Accountmanage.objects.get(pk=saleraccount)

        for item in data.list:
            print(item)
            P = Product.objects.get(pk=item.productno)
            Shoppingcar.objects.filter(customeraccount=C, saleraccount=S, productno=P).delete()
        res = {'code': 200, 'message': '删除成功'}
        return HttpResponse(json.dumps(res))


    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 查看未发货订单
@api_view(['POST'])
def cunshippedOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from saleorder,include,saler,sale,product where saleorder.orderno=include.orderno and include.productno=product.productno and saleorder.saleraccount"
            "=sale.saleraccount and saleorder.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount and sale.productno=product.productno "
            "and orderstatus='unshipped'and customeraccount=" + customeraccount)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 查看已发货订单
@api_view(['POST'])
def cshippedOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        print('5555')
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from saleorder,include,saler,sale,product where saleorder.orderno=include.orderno and include.productno=product.productno and saleorder.saleraccount"
            "=sale.saleraccount and saleorder.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount and sale.productno=product.productno "
            "and orderstatus='shipped'and customeraccount=" + customeraccount)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 查看历史订单
@api_view(['POST'])
def historyOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from saleorder,include,saler,sale,product where saleorder.orderno=include.orderno and include.productno=product.productno and saleorder.saleraccount"
            "=sale.saleraccount and saleorder.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount and sale.productno=product.productno "
            "and orderstatus='served'and customeraccount=" + customeraccount)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 查看所有订单
@api_view(['POST'])
def allOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from saleorder,include,saler,sale,product where saleorder.orderno=include.orderno and include.productno=product.productno and saleorder.saleraccount"
            "=sale.saleraccount and saleorder.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount and sale.productno=product.productno "
            "and customeraccount=" + customeraccount)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 详细查看某一订单
@api_view(['POST'])
def uniOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        account = get_username(data.token)
        role = get_username(data.token)
        orderno = str(data.orderno)
        cursor = connection.cursor()
        cursor.execute(
            "select * from saleorder,include,saler,sale,product where saleorder.orderno=include.orderno and include.productno=product.productno and saleorder.saleraccount"
            "=sale.saleraccount and saleorder.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount and sale.productno=product.productno "
            "and saleorder.orderno=" + orderno)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 收货操作
@api_view(['POST'])
def receive(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        account = get_username(data.token)
        role = get_username(data.token)
        orderno = str(data.orderno)
        cursor = connection.cursor()
        cursor.execute("update saleorder set orderstatus='served' where orderno=" + orderno)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 评价
@api_view(['POST'])
def evalution(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        account = get_username(data.token)
        role = get_username(data.token)
        orderno = str(data.orderno)
        service = str(data.service)
        productQuality = str(data.productquality)
        content = str(data.content)
        figure = "1"
        Evalution.objects.create(orderno=Saleorder.objects.get(pk=orderno),
                                 service = service,
                                 productquality = productQuality,
                                 content = content,
                                 figure = figure,
                                 times = time.strftime('%Y-%m-%d %X', time.localtime(time.time())) )
        data = {'code': 200, 'message': '评价成功'}
        return HttpResponse(json.dumps(data))
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 查看支出
@api_view(['POST'])
def expend(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select sum(totalPrice) from saleorder where customerAccount=" + customeraccount + " and orderstatus is not null")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 发送聊天记录
@api_view(['POST'])
def cusChat(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        customeraccount = get_username(data.token)
        role = get_username(data.token)
        saleraccount = str(data.saleraccount)
        content = str(data.content)
        figure = str(data.figure)
        cursor = connection.cursor()
        cursor.execute(
            "insert into chat(sender,receiver,content,figure) values(" + customeraccount + "," + saleraccount + "," + content + "," + figure + ")")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


@api_view(['POST'])
def insertChat(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        S = Accountmanage.objects.get(pk=get_username(data.token))
        R = Accountmanage.objects.get(pk=data.oaccount)
        content = data.content
        figure = '1'
        Chat.objects.create(sender=S, receiver=R, content=content, figure=figure,
                            chatdate=time.strftime('%Y-%m-%d %X', time.localtime(time.time())))
        data = {'code': 200, 'message': ''}
        return HttpResponse(json.dumps(data))

    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###浏览服装产品
@api_view(['GET'])
def cloth(request):
    cursor = connection.cursor()
    cursor.execute(
        "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount and product.productclassify='服装'")
    rows = dictfetchall(cursor)
    return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})


###浏览食品产品
@api_view(['GET'])
def food(request):
    cursor = connection.cursor()
    cursor.execute(
        "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount and product.productclassify='食品'")
    rows = dictfetchall(cursor)
    return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})


###浏览电子产品
@api_view(['GET'])
def electronic(request):
    cursor = connection.cursor()
    cursor.execute(
        "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount and product.productclassify='电子'")
    rows = dictfetchall(cursor)
    return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})



###浏览生活用品产品
@api_view(['GET'])
def life(request):
    data = UnJson(request.data)
    cursor = connection.cursor()
    cursor.execute(
        "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount and product.productclassify='生活用品'")
    rows = dictfetchall(cursor)
    return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    nse(json.dumps(data))


####################################################################生产者操作#############################

####################################################################生产者操作#############################


##查看自己所发布全部产品
@api_view(['POST'])
def storeProduct(request):
    print("11111")
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount and saler.saleraccount='" + saleraccount + "'")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


##新建产品信息
@api_view(['POST'])
def insertProduct(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        pic1 = str(data.pic1)
        pic2 = str(data.pic2)
        productno = str(data.productname)
        unitprice = str(data.unitprice)
        quantity = str(data.quantity)
        productintroduction = str(data.productintroduction)
        productclassify = str(data.productclassify)
        cursor = connection.cursor()
        cursor.callproc('insertProc', (
            saleraccount, pic1, pic2, productno, unitprice, quantity, productintroduction, productclassify))
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


##编辑产品信息
@api_view(['POST'])
def updateProduct(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        pic1 = str(data.pic1)
        pic2 = str(data.pic2)
        productno = str(data.productno)
        unitprice = str(data.unitprice)
        quantity = str(data.quantity)
        productintroduction = str(data.productintroduction)
        productclassify = str(data.productclassify)
        cursor = connection.cursor()
        cursor.callproc('updateProc', (
            saleraccount, pic1, pic2, productno, unitprice, quantity, productintroduction, productclassify))
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


##删除产品信息
@api_view(['POST'])
def deleteProduct(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        productno = str(data.productno)
        cursor = connection.cursor()
        cursor.callproc('deleteProc', (saleraccount, productno))
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


##查看收藏本店铺的消费者
@api_view(['POST'])
def colCustomer(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute("select * from collection where saleraccount=" + saleraccount)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 查看未发货订单
@api_view(['POST'])
def unshippedOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from saleorder,include a,saler,sale,product where saleorder.orderno=a.orderno and a.productno=product.productno and saleorder.saleraccount=sale.saleraccount "
            "and saleorder.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount and sale.productno=product.productno and orderstatus='unshipped'"
            "and a.productNo=(select productno from include b where a.orderNo=b.orderNo limit 1)and saleorder.saleraccount=" + saleraccount)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 查看已发货订单
@api_view(['POST'])
def shippedOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from saleorder,include a,saler,sale,product where saleorder.orderno=a.orderno and a.productno=product.productno and saleorder.saleraccount=sale.saleraccount "
            "and saleorder.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount and sale.productno=product.productno and orderstatus='shipped'"
            "and a.productNo=(select productno from include b where a.orderNo=b.orderNo limit 1)and saleorder.saleraccount=" + saleraccount)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 查看已收货订单
@api_view(['POST'])
def servedOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        cursor = connection.cursor()
        cursor.execute(
            "select * from saleorder,include a,saler,sale,product where saleorder.orderno=a.orderno and a.productno=product.productno and saleorder.saleraccount=sale.saleraccount "
            "and saleorder.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount and sale.productno=product.productno and orderstatus='served'"
            "and a.productNo=(select productno from include b where a.orderNo=b.orderNo limit 1)and saleorder.saleraccount=" + saleraccount)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 详细查看某一订单
@api_view(['POST'])
def detailOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        account = get_username(data.token)
        role = get_username(data.token)
        orderno = str(data.orderno)
        cursor = connection.cursor()
        cursor.execute(
            "select * from saleorder,include,saler,sale,product where saleorder.orderno=include.orderno and include.productno=product.productno and saleorder.saleraccount"
            "=sale.saleraccount and saleorder.saleraccount=saler.saleraccount and sale.saleraccount=saler.saleraccount and sale.productno=product.productno "
            " and  saleorder.orderno=" + orderno)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 发货操作
@api_view(['POST'])
def deliver(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        account = get_username(data.token)
        role = get_username(data.token)
        orderno = str(data.orderno)
        cursor = connection.cursor()
        cursor.execute("update saleorder set orderstatus='shipped' where orderno=" + orderno)
        rows = dictfetchall(cursor)
        JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})

        data = {'code': 400, 'message': '成功'}
        return HttpResponse(json.dumps(data))
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 查看订单评价
@api_view(['POST'])
def evaOrder(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        account = get_username(data.token)
        role = get_username(data.token)
        orderno = str(data.orderno)
        cursor = connection.cursor()
        cursor.execute("select * from evalution where orderno=" + orderno)
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


# 发送聊天记录
@api_view(['POST'])
def salChat(request):
    data = UnJson(request.data)
    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        customeraccount = str(data.customeraccount)
        content = str(data.content)
        figure = str(data.figure)
        cursor = connection.cursor()
        cursor.execute(
            "insert into chat(sender,receiver,content,figure) values(" + saleraccount + "," + customeraccount + "," + content + "," + figure + ")")
        rows = dictfetchall(cursor)
        return JsonResponse(rows, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))


###浏览单个产品信息并加入历史记录
@api_view(['POST'])
def suniProduct(request):
    data = UnJson(request.data)

    if check_token(data.token):  # 判断通行证是否合法
        saleraccount = get_username(data.token)
        role = get_username(data.token)
        productno = str(data.productno)
        # token = str(data.token)

        cursor = connection.cursor()
        cursor.execute(
            "select * from product,saler,sale where product.productno=sale.productno and sale.saleraccount=saler.saleraccount and saler.saleraccount=" + saleraccount + " and product.productno=" + productno)
        row = dictfetchall(cursor)
        return JsonResponse(row, safe=False, json_dumps_params={'ensure_ascii': False})
    else:
        data = {'code': 402, 'message': '请登入'}
        return HttpResponse(json.dumps(data))
